package com.zc.framework.persistence.interceptor;

import com.zc.framework.persistence.dialect.Dialect;
import com.zc.framework.persistence.dialect.db.DB2Dialect;
import com.zc.framework.persistence.dialect.db.MySQLDialect;
import com.zc.framework.persistence.dialect.db.OracleDialect;
import com.zc.framework.persistence.dialect.db.PostgreSQLDialect;
import com.zc.framework.persistence.pagination.ViewPage;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.util.Properties;

/**
 * Mybatis分页拦截器基类
 * Created by zc on 2016/8/31.
 */
public abstract class BaseInterceptor  implements Interceptor, Serializable {

    private static final long serialVersionUID = -4987373656428236904L;

    protected static final String PAGE = "page";

    protected static final String DELEGATE = "delegate";

    protected static final String MAPPED_STATEMENT = "mappedStatement";

    protected static Logger logger = LogManager.getLogger(BaseInterceptor.class);

    protected Dialect dialect;

    public void initProperties(Properties properties) {
        Dialect dialect = null;
        String dbType = properties.getProperty("dialect");
        if("db2".equals(dbType)){
            dialect = new DB2Dialect();
        } else if("mysql".equals(dbType)){
            dialect = new MySQLDialect();
        } else if("oracle".equals(dbType)){
            dialect = new OracleDialect();
        } else if("postgresql".equals(dbType)){
            dialect = new PostgreSQLDialect();
        }
        if (dialect == null) {
            throw new RuntimeException("mybatis dialect error.");
        }
        this.dialect = dialect;
    }

    protected static ViewPage<Object> convertParameter(Object parameterObject, ViewPage<Object> page) {
        try{
            if (parameterObject instanceof ViewPage) {
                return (ViewPage<Object>) parameterObject;
            } else {
                return (ViewPage<Object>) FieldUtils.readField(parameterObject, PAGE);
            }
        }catch (Exception e) {
            return null;
        }
    }
}
